<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Forms\CouponForm;
use App\Http\Forms\UserCouponForm;
use App\Modules\Coupon\Models\Coupon;
use App\Modules\Coupon\Models\UserCoupon;
use App\Modules\Good\Models\Good;
use App\Modules\Package\Models\GoodPackage;
use App\Modules\Shop\Manager;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CouponController extends ApiController
{
    public function index()
    {
        $this->authorize('coupon');
        $shop = Manager::getShop();
        $data = Coupon::query()
            ->paginate(50);
        foreach ($data as $item) {
            if (!empty($item->applicable)) {
                if ($item->type == Coupon::TYPE_PACKAGE) {
                    $item->applicable = implode(",", GoodPackage::query()->find($item->applicable)->pluck('name')->all());
                } else {
                    $item->applicable = implode(",", Good::query()->find($item->applicable)->pluck('name')->all());
                }
            }
        }
        $sidebar = 'index';
        return view('coupon.index', compact('data', 'shop', 'sidebar'));
    }

    public function create()
    {
        $this->authorize('coupon-edit');
        $shop = Manager::getShop();
        $form = $this->form(CouponForm::class, [
            'method' => 'PUT',
            'url' => route('admin.coupon.store'),
        ], [
            'shop' => $shop->pluck('name', 'id')->all(),
            'linkId' => [],
            'applicable' => [],
        ]);
        $sidebar = 'index';
        return view('coupon.form', compact('form', 'sidebar'));
    }

    public function store()
    {
        $this->authorize('coupon-edit');
        $form = $this->form(CouponForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['price_limit'] = $data['price_limit'] * 100;
        $data['money'] = $data['money'] * 100;
        $shop = Shop::query()->find($data['shop_id']);
        $data['type'] = $shop->type == Shop::TYPE_PHOTO? Coupon::TYPE_PACKAGE : Coupon::TYPE_GOOD;
        Coupon::query()->create($data);
        return redirect()->route('admin.coupon.index');
    }

    public function edit($id)
    {
        $this->authorize('coupon-edit');
        $shop = Manager::getShop();
        $model = Coupon::query()->where('id', $id)->first();
        $model->price_limit = $model->price_limit / 100;
        $model->money = $model->money / 100;
        $applicable = [];
        if ($model->type == Coupon::TYPE_PACKAGE) {
//            $link = GoodPackage::query()->find($model->link_id)->pluck('name', 'id')->all();
            if (!empty($model->applicable)) {
                $applicable = GoodPackage::query()->find($model->applicable)->pluck('name', 'id')->all();
            }
        } else {
//            $link = Good::query()->find($model->link_id)->pluck('name', 'id')->all();
            if (!empty($model->applicable)) {
                $applicable = GoodPackage::query()->find($model->applicable)->pluck('name', 'id')->all();
            }
        }

        $form = $this->form(CouponForm::class, [
            'method' => 'POST',
            'url' => route('admin.coupon.update', ['id' => $id]),
            'model' => $model,
        ], [
            'shop' => $shop->pluck('name', 'id')->all(),
//            'linkId' => $link,
            'applicable' => $applicable,
        ]);
        $sidebar = 'index';
        return view('coupon.form', compact('form', 'sidebar'));
    }

    public function setGift($id)
    {
        Coupon::query()
            ->where('is_gift', 1)
            ->update([
                'is_gift' => 0
            ]);
        Coupon::query()
            ->where('id', $id)
            ->update([
                'is_gift' => 1,
            ]);
        return redirect()->route('admin.coupon.index');
    }

    public function update($id)
    {
        $coupon = Coupon::query()->where('id', $id)->first();
        $form = $this->form(CouponForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['price_limit'] = $data['price_limit'] * 100;
        $data['money'] = $data['money'] * 100;
        $shop = Shop::query()->find($data['shop_id']);
        $data['type'] = $shop->type == Shop::TYPE_PHOTO? Coupon::TYPE_PACKAGE : Coupon::TYPE_GOOD;
        $coupon->update($data);
        return redirect()->route('admin.coupon.index');
    }

    public function deleteCoupon($id)
    {
        $this->authorize('coupon-edit');
        Coupon::query()->where('id', $id)->delete();
        return redirect()->route('admin.coupon.index');
    }

    public function userCoupon()
    {
        $this->authorize('coupon-record');
        $data = UserCoupon::query()
            ->paginate(20);

        $user = User::query()->find($data->pluck('user_id')->all())->keyBy('id');
        $sidebar = 'user_coupon';
        return view('coupon.user_coupon', compact('data', 'user', 'sidebar'));
    }

    public function sendForm()
    {
        $this->authorize('coupon-record-edit');
        $coupon = Coupon::query()->get()->pluck('title', 'id')->all();
        $form = $this->form( UserCouponForm::class, [
            'method' => 'PUT',
            'url' => route('admin.coupon.user.send'),
        ], [
            'coupon' => $coupon,
        ]);
        $sidebar = 'user_coupon';
        return view('coupon.form', compact('form', 'sidebar'));
    }

    public function send()
    {
        $this->authorize('coupon-record-edit');
        $form = $this->form(UserCouponForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        /** @var Coupon $coupon */
        $coupon = Coupon::query()->find($data['coupon_id']);
        foreach ($data['user'] as $userId) {
            UserCoupon::query()
                ->create([
                    'shop_id' => $coupon->shop_id,
                    'user_id' => $userId,
                    'coupon_id' => $coupon->id,
                    'type' => $coupon->type,
                    'title' => $coupon->title,
                    'price_limit' => $coupon->price_limit,
                    'money' => $coupon->money,
                    'applicable' => $coupon->applicable,
                    'expiration_date' => Carbon::now()->addDays($coupon->shelf_life)->toDateTimeString(),
            ]);
        }

        return redirect()->route('admin.coupon.user.index');
    }

    public function cancelUserCoupon($id)
    {
        $this->authorize('coupon-record-edit');
        $userCoupon = UserCoupon::query()
            ->where('id', $id)
            ->first();
        if (!is_null($userCoupon->use_id)) {
            return redirect()->back()->withErrors("已经使用的优惠券不能删除");
        }
        $userCoupon->delete();
        return $this->success();
    }

}
